package com.xd.common.filter;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xd.common.constant.SysConstant;
import com.xd.common.util.IpUtils;
import com.xd.common.util.JwtUtil;
import com.xd.core.note.ICacheService;
import com.xd.core.system.entity.LoginUser;
import com.xd.core.system.entity.SysPermission;
import com.xd.core.system.entity.SysUser;
import com.xd.core.system.mapper.SysPermissionMapper;
import com.xd.core.system.mapper.SysUserMapper;
import com.xd.core.system.service.ISysPermissionService;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Component
@Slf4j
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    @Autowired
    private SysPermissionMapper sysPermissionMapper;
    @Autowired
    private ICacheService iCacheService;
    private static final String redisLogin = "login:";
    private static final String redisToken = "token:";
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
//        String requestURI = request.getRequestURI();//登录和验证码和插入客户信息
        String token = request.getHeader("token");
        if (!StringUtils.hasText(token)) {
            //放行
            filterChain.doFilter(request, response);
            return;
        }
        //解析token
        JSONObject jwtToken = null;
        try {
            Claims claims = JwtUtil.parseJWT(token);
            String subject = claims.getSubject();
            jwtToken = JSONObject.parseObject(subject);
        } catch (Exception e) {
            //log.error("非法token值为：" + token);
            request.setAttribute("msg", "用户登录已过期");
            //throw new XkdException("用户登录已过期");
            log.info("用户登录已过期 IP:" + IpUtils.getClientIpAddr(request));
            filterChain.doFilter(request, response);
            return;
        }

        //从redis中获取用户信息
        String sysType = jwtToken.getString("sysType");
        if (!SysConstant.SYSTEM_TYPE_WEB.equals(sysType)){
            filterChain.doFilter(request, response);
            return;
        }
        String userid = jwtToken.getString("userid");
        String redisKey = redisLogin + userid;
        String tokenKey = redisToken + userid;
        LoginUser loginUser = (LoginUser) redisTemplate.opsForValue().get(redisKey);
        String tokenOld = (String) redisTemplate.opsForValue().get(tokenKey);
        //调用接口的IP和redis存的IP不一致
        if (Objects.isNull(loginUser)) {
            request.setAttribute("msg", "用户长时间未操作请重新登陆");
            log.info("用户:" + userid + " 已失效");
            filterChain.doFilter(request, response);
            return;
        }
        if (!token.equals(tokenOld)) {//判断token是否是同一个
            request.setAttribute("msg", "账号在其他地方登录");
            log.info("用户:" + userid + " 在其他地方登录");
            filterChain.doFilter(request, response);
            return;
        }
        //封装Authentication对象存入SecurityContextHolder
        //TODO 获取权限信息封装到Authentication中
        //缓存里取最新权限
        //每次都获取最新权限查库
        List<SysPermission> sysPermission = iCacheService.selectSysperms(Integer.valueOf(userid));
//        List<SysPermission> sysPermission = sysPermissionMapper.selectSysperms(Integer.valueOf(userid), null);
        List<String> pers = sysPermission.stream().map(SysPermission::getPerms).collect(Collectors.toList());
        List<SimpleGrantedAuthority> authorities = pers.stream().
                map(SimpleGrantedAuthority::new).
                collect(Collectors.toList());
        loginUser.setAuthorities(authorities);
        loginUser.setPermissions(pers);
        loginUser.setSysPermission(sysPermission);
        UsernamePasswordAuthenticationToken authenticationToken =
                new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //刷新token和用户信息过期时间
        redisTemplate.opsForValue().set(redisKey, loginUser, 60 * 2, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(tokenKey, token, 60 * 2, TimeUnit.MINUTES);
        //放行
        filterChain.doFilter(request, response);
    }
}
